package com.example.system.controller;

import com.example.system.common.Result;
import com.example.system.entity.Health;
import com.example.system.exception.CustomException;
import com.example.system.service.impl.HealthServiceImpl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/health")
@MapperScan("com.*.mapper")
public class HealthController {
    @Autowired
    private HealthServiceImpl healthService;

    // 根据用户Id查用户健康信息
    @GetMapping("/search/{userId}")
    public Result findHealthByUserId(@PathVariable Integer userId) {
        List<Health> healthList = healthService.findHealthByUserID(userId);
        if (healthList == null || healthList.isEmpty()) {
            return Result.error("尚未检测过当前用户的健康信息");
        }
        return Result.success(healthList);
    }

    // 根据用户Id及时间区间查询健康信息
    @GetMapping("/search/timeRange/{userId}")
    public Result findHealthByUserIdAndTimeRange(
            @PathVariable Integer userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime beginTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        List<Health> healthList;
        try {
            healthList = healthService.findHealthByUserIDAndTimeRange(userId, beginTime, endTime);
        } catch (CustomException e) {
            return Result.error(e.getMsg());
        }
        return Result.success(healthList);
    }

    // 新增用户健康信息
    @PostMapping("/add")
    public Result addHealthByHealth(@RequestBody Health health) {
        try {
            healthService.addHealthByHealth(health);
        } catch (CustomException e) {
            return Result.error(e.getMsg());
        }
        return Result.success();
    }

    // 根据用户Id删除健康信息
    @DeleteMapping("/delete/{userId}")
    public Result deleteHealthByUserId(@PathVariable Integer userId) {
        try {
            healthService.deleteHealthByUserId(userId);
        } catch (CustomException e) {
            return Result.error(e.getMsg());
        }
        return Result.success();
    }

    // 根据用户Id及时间区间删除健康信息
    @DeleteMapping("/delete/timeRange/{userId}")
    public Result deleteHealthByUserIdAndTimeRange(
            @PathVariable Integer userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime beginTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        try {
            healthService.deleteHealthByUserIdAndTimeRange(userId, beginTime, endTime);
        } catch (CustomException e) {
            return Result.error(e.getMsg());
        }
        return Result.success();
    }
}

